package com.siqi.hr.system.organization.controller;

import com.siqi.hr.common.Constants;
import com.siqi.hr.common.controller.Users;
import com.siqi.hr.common.utils.Const;
import com.siqi.hr.common.utils.TableConstant;
import com.siqi.hr.system.common.enums.FieldEditPageEnum;
import com.siqi.hr.system.common.enums.OperationEnum;
import com.siqi.hr.system.common.model.Module;
import com.siqi.hr.system.common.model.ModuleType;
import com.siqi.hr.system.common.model.ReturnInfo;
import com.siqi.hr.system.common.model.filter.QueryDataEntity;
import com.siqi.hr.system.common.service.CommonOperationService;
import com.siqi.hr.system.common.utils.Common;
import com.siqi.hr.system.common.utils.QueryDataUtil;
import com.siqi.hr.system.custom.entity.EntityOperation;
import com.siqi.hr.system.custom.entity.EntityRecord;
import com.siqi.hr.system.custom.entity.FieldRecord;
import com.siqi.hr.system.custom.service.EntityOperationService;
import com.siqi.hr.system.custom.service.EntityRecordService;
import com.siqi.hr.system.custom.service.FieldEmployeeService;
import com.siqi.hr.system.organization.entity.Employee;
import com.siqi.hr.system.organization.entity.Role;
import com.siqi.hr.system.organization.service.DeptService;
import com.siqi.hr.system.organization.service.EmployeeService;
import com.siqi.hr.system.organization.service.RoleService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

/**
 * 员工信息维护控制器
 * @author     xiaogq
 * @date       2016-07-21
 */
@Controller
@RequestMapping("Employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private FieldEmployeeService fieldEmployeeService;
    @Autowired
    private CommonOperationService commonOperationService;
    @Autowired
    private EntityOperationService entityOperationService;
    @Autowired
    private EntityRecordService entityRecordService;

    /**
     * 登陆系统
     *@author xiaogq 2016-07-21
     *@param
     *@return
     */
    @RequestMapping(value="queryLogin")
    @ResponseBody
    public ReturnInfo queryLogin(HttpServletRequest request, HttpSession session, Employee employee) throws Exception {
        String pwd = employee.getPassword() == null ? "" : employee.getPassword();
        employee.setPassword(pwd);
        session.setMaxInactiveInterval(60*60*1);  // 设置Session有效时间为1小时
        //验证登陆用户名、密码是否正确
        ReturnInfo info = employeeService.checkLogin(request,session,employee);
        return info;
    }

    /**
     * 登陆模块
     *@author xiaogq 2016-07-21
     *@param
     *@return
     */
    @RequestMapping(value = "loginModule", method= RequestMethod.GET)
    public ModelAndView loginModule(HttpServletRequest request, HttpSession session) throws Exception {
        //从session中获取当前登陆用户信息
        Employee emp = (Employee)request.getSession().getAttribute("emp");
        Object object = request.getSession().getAttribute("pSiqiUser");
        Users pSiqiUser = new Users();
        if(null == object){
            pSiqiUser.setName(emp.getName());
            pSiqiUser.setPhone(emp.getPhone());
            pSiqiUser.setEmail(emp.getEmail());
            pSiqiUser.setUserName(emp.getJobNumber());
            request.getSession().setAttribute("pSiqiUser",pSiqiUser);
        }
        //员工登陆的模块(1:系统设置模块,2:业务模块)
        int moduleId = request.getParameter("moduleid") == null ? 1 : Integer.parseInt(request.getParameter("moduleid"));
        List<Module> mlist = null;
        //获取角色可登陆的模块(数据格式为：11，第一位代表系统设置模块，第二位代表业务模块，以此类推)
        String rolemodule = emp.getRole().getLoginModule();
        if(StringUtils.isNotBlank(rolemodule)){
            mlist = roleService.getListRoleModule(rolemodule);
        }else{
            mlist = roleService.getRoleModule(new Role(emp.getRole().getId()));
        }
        //判断当前登录员工对实体是否有查看（也就是访问）操作权限（true：有，false ：没有）肖功钦添加
        //Boolean viewAuth =  AuthorityMrg.getInstance().match(emp.getRole().getId(),TableConstant.EMPLOYEE_TCODE,OperatType.VIEW);
        ModelAndView mav = new ModelAndView();
        mav.addObject("emp",emp);
        mav.addObject("moduleId",moduleId);
        mav.addObject("moduleName", ModuleType.getModuleType(moduleId).getDesc());
        mav.addObject("mlist",mlist);
        //mav.setViewName("common/layout/frame");
        mav.setViewName("common/layout/miniui/miniui_frame");
        return mav;
    }

    /**
     * 用户登出
     *@author xiaogq 08 8, 2016
     *@param
     *@return
     */
    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response, HttpSession session) throws ServletException, IOException {
        //获取Session中用户信息
        Employee emp = (Employee) session.getAttribute("emp");
        session.invalidate();
        response.sendRedirect(request.getContextPath()+"/login.jsp");
    }

    /**
     * 初始化员工桌面数据 version2.0
     * @author xiaogq Jul 11, 2014
     * @param request
     * @param session
     * @return
     */
    @RequestMapping(value="initUserDesk")
    public ModelAndView initUserDeskVersTwo(HttpServletRequest request, HttpSession session){
        Employee emp = (Employee)session.getAttribute("emp");
        ModelAndView mav = new ModelAndView();
        //获取模块id
        int moduleId = request.getParameter("moduleId") == null ? 1 : Integer.parseInt(request.getParameter("moduleId"));
        mav.addObject("moduleId",moduleId);
        if(moduleId == ModuleType.SETTING.getCode()){	//系统设置
            mav.setViewName("common/layout/bus_home");
        }else { // 业务模块
            mav.setViewName("common/layout/bus_home");
        }
        return mav;
    }

    /**
     * 初始化用户列表页面
     * @param session
     * @return
     */
    @RequestMapping(value = "initEmployee", method = RequestMethod.GET)
    public ModelAndView initDept(HttpSession session) throws Exception{
        ModelAndView mav = new ModelAndView();
        Employee emp = (Employee) session.getAttribute("emp");
        //获取头部列表操作按钮
        List<EntityOperation> listButtons = entityOperationService.queryEntityOperationByHere(emp.getRole(), TableConstant.EMPLOYEE_TCODE, OperationEnum.showList);
        //获取员工头部
        Map<String,Object> columnMap = fieldEmployeeService.getEntityColumns(emp,TableConstant.EMPLOYEE_TCODE, true,true);
        mav.addObject("listButtons",listButtons);
        mav.addObject("columns",columnMap.get("columns"));
        mav.addObject("fields", columnMap.get("fields"));
        mav.addObject("entity", new EntityRecord(TableConstant.EMPLOYEE_TCODE,"员工"));
        mav.setViewName("system/organization/employee/employee_list");
        return mav;
    }

    /**
     * 获取用户列表数据(xiaoxm)
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "queryEmployeeAll")
    @ResponseBody
    public Map<String,Object> queryEmployeeAll(HttpSession session, HttpServletRequest request) throws Exception{
        //获取搜索条件、当前登录用户、部门以及分页数据信息
        QueryDataEntity queryData = QueryDataUtil.getQueryDataEntity(request);
        //设置列表数据分页查询
        queryData.setUsepager(true);
        queryData.setBootstrapQuery(true);
        queryData.setSearchIds(Constants.ROOTEMPID);
        //获取列头操作按钮
        List<EntityOperation> colButtons = entityOperationService.queryEntityOperationByHere(queryData.getEmployee().getRole(), TableConstant.EMPLOYEE_TCODE, OperationEnum.showColumn);
        Map<String, Object> resultMap =  commonOperationService.queryCustomObjectAll(queryData);
        //处理可登录模块字段
        List<Map<String, Object>> datasResult = (List<Map<String, Object>>) resultMap.get(Const.ROWS);
        for(Map<String, Object> map : datasResult){
            List<EntityOperation> operationList = new ArrayList<EntityOperation>();
            for(EntityOperation operation : colButtons){
                operationList.add(operation);
            }
            String rootEmpId = map.get("id") == null ? "" : map.get("id").toString();
            //处理列前操作如果是管理员id则没有删除按钮
            if(rootEmpId.equals(Constants.ROOTEMPID)){
                EntityOperation operation = new EntityOperation("删除","fun_delete","","glyphicon glyphicon-trash",OperationEnum.showColumn.name(),new EntityRecord(TableConstant.EMPLOYEE_TCODE));
                operationList.remove(operation);
            }
            EntityOperation clearPwdOper = new EntityOperation("清空密码","fun_clearUppw","","glyphicon glyphicon-erase",OperationEnum.showColumn.name(),new EntityRecord(TableConstant.EMPLOYEE_TCODE));
            operationList.add(clearPwdOper);
            //处理列前操作停用/启用按钮按钮
            for (String key : map.keySet()) {
                //处理列表列前停用/启用操作
                if(key.equals(Const.FLAG_BIT)){
                    EntityOperation operation = null;
                    if(map.get(key).equals("停用")){
                        operation = new EntityOperation("停用","fun_disable","","glyphicon glyphicon-play", OperationEnum.showColumn.name(),new EntityRecord(TableConstant.EMPLOYEE_TCODE));
                    }else{
                        operation = new EntityOperation("启用","fun_enable","","glyphicon glyphicon-pause",OperationEnum.showColumn.name(),new EntityRecord(TableConstant.EMPLOYEE_TCODE));
                    }
                    operationList.remove(operation);
                }
            }
            //添加列表列前操作按钮
            map.put("operation", operationList);
        }
        return resultMap;
    }

    /**
     * 获取用户列表数据(xiaoxm)
     * @param session
     * @param request
     * @return
     */
    @RequestMapping(value = "queryRoleRelateEmpAll")
    @ResponseBody
    public Map<String,Object> queryRoleRelateEmpAll(HttpSession session, HttpServletRequest request) throws Exception{
        //获取搜索条件、当前登录用户、部门以及分页数据信息
        QueryDataEntity queryData = QueryDataUtil.getQueryDataEntity(request);
        //设置列表数据分页查询
        queryData.setUsepager(false);
        queryData.setBootstrapQuery(true);
        //获取列头操作按钮
        List<EntityOperation> colButtons = new ArrayList<EntityOperation>();
        EntityOperation operation = new EntityOperation("查看","fun_view_employee","Employee/employeeView.do","glyphicon glyphicon-search", OperationEnum.showColumn.name(),new EntityRecord(TableConstant.EMPLOYEE_TCODE));
        colButtons.add(operation);
        Map<String, Object> resultMap =  commonOperationService.queryCustomObjectAll(queryData);
        //处理可登录模块字段
        List<Map<String, Object>> datasResult = (List<Map<String, Object>>) resultMap.get(Const.ROWS);
        for(Map<String, Object> map : datasResult){
            //添加列表列前操作按钮
            map.put("operation", colButtons);
        }
        return resultMap;
    }

    /**
     * 添加员工初始化
     * @return
     */
    @RequestMapping(value = "employeeAddInit", method = RequestMethod.GET)
    public ModelAndView employeeAddInit(HttpServletRequest request) throws Exception{
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        //获取员工最大工号(编号)值加一
        int jobNumber = employeeService.getMaxJobNumber(TableConstant.EMPLOYEE_TNAME)+1;
        //根据实体id、角色id获取添加，编辑页显示字段
        List<FieldRecord> fields = commonOperationService.getEditOrViewPageFields(TableConstant.EMPLOYEE_TCODE, emp.getRole().getId(),FieldEditPageEnum.hidden_edit);
        List<Map<String, Object>> fieldRecords = commonOperationService.getEditPageFields(TableConstant.EMPLOYEE_TCODE,fields);
        //获取有效的所有组织(部门)数据
        JSONArray dataArray = deptService.queryDeptTree(TableConstant.DEPT_TNAME);
        ModelAndView andView = new ModelAndView();
        andView.addObject("entityId", TableConstant.EMPLOYEE_TCODE);
        andView.addObject("fieldRecords", fieldRecords);
        andView.addObject("jobNumber", Common.getMaxJobNumber(jobNumber));
        andView.addObject("deptDatas",dataArray);
        andView.addObject("saveUrl", "Employee/employeeSave.do");
        andView.setViewName("system/organization/employee/employee_add");
        return andView;
    }

    /**
     * 添加员工保存方法
     * @author
     * @Return ModelAndView
     */
    @RequestMapping(value="employeeSave", method = RequestMethod.POST)
    @ResponseBody
    public String employeeSave(HttpServletRequest request, DefaultMultipartHttpServletRequest multipartRequest) throws Exception{
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        EntityRecord entity = entityRecordService.queryEntityRecordById(TableConstant.EMPLOYEE_TCODE);
        //获取前端传过来的form表单值
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,Object> dataMap = new LinkedHashMap<String,Object>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey().toString();
            String[] value=(String[])entry.getValue();
            if(!key.equals("entityId")) {
                dataMap.put(key,value[0]);
            }
        }
        JSONObject balkJson = new JSONObject();
        int counts = employeeService.addSaveEmployee(dataMap, entity, emp, multipartRequest);
        if(counts > 0){
            balkJson.put("success","success");
        }else{
            balkJson.put("error","error");
        }
        return balkJson.toString();
    }

    /**
     * 修改员工页面初始化
     * @return
     */
    @RequestMapping(value = "employeeEditInit", method = RequestMethod.GET)
    public ModelAndView employeeEditInit(String id, HttpServletRequest request) throws Exception{
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        EntityRecord entity = new EntityRecord(TableConstant.EMPLOYEE_TCODE);
        //根据实体id、角色id获取添加，编辑页显示字段
        List<FieldRecord> fields = commonOperationService.getEditOrViewPageFields(TableConstant.EMPLOYEE_TCODE, emp.getRole().getId(),FieldEditPageEnum.hidden_edit);
        List<Map<String, Object>> fieldRecords = commonOperationService.getEditPageFields(TableConstant.EMPLOYEE_TCODE,fields);
        //根据id获取该记录id
        Map<String, Object> datasMap = commonOperationService.queryTDataInfoById(TableConstant.EMPLOYEE_TCODE,id,fields);
        List<Long> deptIdList = new ArrayList<Long>();
        String deptIds = datasMap.get("pk_t_2_1") == null ? "0" : datasMap.get("pk_t_2_1").toString();
        if(StringUtils.isNotBlank(deptIds)){
            deptIdList.add(Long.parseLong(deptIds));
        }
        //获取有效的所有组织(部门)数据
        JSONArray dataArray = deptService.queryDeptTree(TableConstant.DEPT_TNAME);
        ModelAndView andView = new ModelAndView();
        andView.addObject("entity", entity);
        andView.addObject("fieldRecords", fieldRecords);
        andView.addObject("datas", datasMap);
        andView.addObject("deptDatas",dataArray);
        andView.addObject("saveUrl", "Employee/employeeEdit.do");
        andView.setViewName("system/organization/employee/employee_edit");
        return andView;
    }

    /**
     * 修改自定义实体保存方法
     * @author         xiaoxm
     * @Return ModelAndView
     */
    @RequestMapping(value="employeeEdit", method = RequestMethod.POST)
    @ResponseBody
    public String employeeEdit(HttpServletRequest request, String id, DefaultMultipartHttpServletRequest multipartRequest) throws Exception{
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        EntityRecord entity = entityRecordService.queryEntityRecordById(TableConstant.EMPLOYEE_TCODE);
        //获取前端传过来的form表单值
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String,Object> dataMap = new LinkedHashMap<String,Object>();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
            String key = entry.getKey().toString();
            String[] value = entry.getValue();
            if (!key.equals("entityId") && !key.equals("id")){
                dataMap.put(key,value[0]);
            }
        }
        JSONObject balkJson = new JSONObject();
        int counts = employeeService.updateEmployeeData(dataMap, entity, emp, id, multipartRequest);
        if(counts > 0){
            balkJson.put("success","success");
        }else{
            balkJson.put("error","error");
        }
        return balkJson.toString();
    }

    /**
     * 删除用户数据
     * @param id
     * @throws Exception
     *
     */
    @RequestMapping(value = "employeeDelete", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject employeeDelete(String id) throws Exception{
        JSONObject balkJson = employeeService.deleteEmployee(TableConstant.EMPLOYEE_TNAME, id);
        return balkJson;
    }

    /**
     * 员工查看页面
     * @param    id         记录id
     * @param    isself    是否是从主页面个人信息点击进入(true：是，false：否)
     * @return
     */
    @RequestMapping(value = "employeeView", method = RequestMethod.GET)
    public ModelAndView employeeView(HttpServletRequest request,String id,Boolean isself) throws Exception{
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        List<EntityOperation> listButtons = new ArrayList<EntityOperation>();
        //获取详情页操作按钮
        List<EntityOperation> viewButtons = entityOperationService.queryEntityOperationByHere(emp.getRole(), TableConstant.EMPLOYEE_TCODE, OperationEnum.showView);
        for(EntityOperation operation : viewButtons){
            if(operation.getIcon().endsWith("-edit")){
                operation.setIcon("image/common/operation/oper_UPDATE.png");
            }else if(operation.getIcon().endsWith("-trash")){
                if(id.equals(Constants.ROOTEMPID)){
                    continue;
                }else{
                    operation.setIcon("image/common/operation/oper_DELETE.png");
                }
            }
            listButtons.add(operation);
        }
        if(isself != null && isself){
            //添加修改密码按钮
            EntityOperation operation = new EntityOperation("修改密码","oper_updatepwd","","image/common/operation/oper_updatePwd.png",OperationEnum.showList.name(),new EntityRecord(TableConstant.EMPLOYEE_TCODE));
            listButtons.add(operation);
        }
        Map<String, Object> resultDataMap = commonOperationService.getViewPageFields(id,TableConstant.EMPLOYEE_TCODE, emp.getRole().getId(),FieldEditPageEnum.hidden_show);
        //获取字段信息
        List<FieldRecord> fieldRecords = (List<FieldRecord>) resultDataMap.get("fieldRecord");
        //获取字段值
        Map<String,Object> datas = (Map<String, Object>) resultDataMap.get("datas");
        ModelAndView andView = new ModelAndView();
        andView.addObject("id",id);
        andView.addObject("entity", new EntityRecord(TableConstant.EMPLOYEE_TCODE,"员工"));
        andView.addObject("listButtons", listButtons);
        andView.addObject("fieldRecords", fieldRecords);
        andView.addObject("datas", datas);
        andView.setViewName("system/organization/employee/employee_view");
        return andView;
    }

    /**
     * 修改登陆密码
     *@author xiaogq 2016-09-22
     *@param
     *@return
     */
    @RequestMapping("updatePwd")
    @ResponseBody
    public Map<String, Object> updatePwd(HttpServletRequest request,HttpServletResponse response, HttpSession session){
        Map<String, Object> map = new HashMap<String, Object>();

        String empid = request.getParameter("empid");
        String oldpwd = request.getParameter("oldpwd");
        String newpwd = request.getParameter("newpwd");

        //验证原密码是否正确
        Boolean pwdConfirm = employeeService.loginPwdConfirm(empid, oldpwd.trim());
        if(pwdConfirm){
            employeeService.updatePwd(empid, newpwd);
        }else{
            map.put("error", "请输入正确原密码！");
        }
        return map;
    }

    /**
     * 清空员工密码
     *@author xiaogq 2016-09-23
     *@param
     *@return
     */
    @RequestMapping("emptyEmployeePassword")
    @ResponseBody
    public Map<String, Object> emptyEmployeePassword(HttpServletRequest request,HttpServletResponse response, HttpSession session){
        Map<String, Object> map = new HashMap<String, Object>();
        Employee emp = (Employee) request.getSession().getAttribute("emp");
        String empId = request.getParameter("employeeId");
        if(StringUtils.isNotEmpty(empId)){
            //当前登录人员为非管理员时不能清空管理员登录密码
            if(empId.equals(Constants.ROOTEMPID) && !empId.equals(emp.getId())){
                map.put("error", "当前员工没有权力清空管理员登录密码！");
            }else{
                employeeService.emptyEmployeePassword(empId);
            }
        }
        return map;
    }

    /**
     * 员工数据停用
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "employeeDisable")
    @ResponseBody
    public String employeeDisable(String id) throws Exception {
        employeeService.disableEmployee(TableConstant.EMPLOYEE_TNAME, id);
        JSONObject balkJson = new JSONObject();
        balkJson.put("success","success");
        return balkJson.toString();
    }

    /**
     * 员工数据启用
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "employeeEnable")
    @ResponseBody
    public String employeeEnable(String id) throws Exception {
        employeeService.enableEmployee(TableConstant.EMPLOYEE_TNAME, id);
        JSONObject balkJson = new JSONObject();
        balkJson.put("success","success");
        return balkJson.toString();
    }
}
